﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Catalogo.Portable.ViewModel;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Windows.Networking.Proximity;
using System.Text;
using System.Runtime.InteropServices.WindowsRuntime;
using Catalogo.Portable.ViewModel.Messages;

namespace Catalogo.WindowsPhone.Views
{
    public partial class HomePage : PhoneApplicationPage
    {
        private ProximityDevice _DispositivoNFC;
        public HomePageViewModel ViewModel
        {
            get
            {
                return DataContext as HomePageViewModel;
            }
        }

        public HomePage()
        {
            InitializeComponent();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (ViewModel == null)
            {
                DataContext = new HomePageViewModel();
                ViewModel.Messenger.Subscribe<NavegarParaPagina>(NavegarParaPaginaMessageHandler.NavegarParaPagina);
                await ViewModel.LoadAsync();
                Panorama.Background = new ImageBrush() { ImageSource = new BitmapImage(new Uri(ViewModel.Empresa.ImageUrl)), Stretch = Stretch.UniformToFill };

                InicializarNFC();
            }
        }

        private void InicializarNFC()
        {
            if (ProximityDevice.GetDefault() != null)
            {
                _DispositivoNFC = ProximityDevice.GetDefault();
                _DispositivoNFC.SubscribeForMessage("Windows.MySubType", TagLida);
            }
        }

        private void TagLida(ProximityDevice sender, ProximityMessage message)
        {
            var buffer = message.Data.ToArray();
            var idItem = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            Dispatcher.BeginInvoke(() =>
            {
                ViewModel.AbrirItemCommand.Execute(idItem);
            });
        }
    }
}